/*
 Example Generated Tests Block Structure (without start/end markers):

 rq.test("Status code is 201", () => {
   rq.response.to.have.status(201);
 });

 rq.test("Request method is POST", () => {
   rq.expect(rq.request.method).to.equal("POST");
 });

 rq.test("Response has valid JSON body", () => {
   rq.response.to.have.jsonBody();
 });

 rq.test("Response body is JSON object", () => {
   const parsed = JSON.parse(rq.response.body);
   rq.expect(parsed).to.be.an("object").and.not.to.be.an("array");
 });
*/

interface BuildTestsOptions {
  method?: string;
  status?: number;
  hasJsonObjectBody?: boolean;
}

export function hasTests(script: string | undefined): boolean {
  if (!script) return false;
  return /(?:^|\n)\s*(?:rq|RQ)\.test\(/.test(script);
}

// Build block lines; only include tests when underlying data available.
// Generates up to 4 common POST tests: status, method, valid JSON, JSON object.
export function buildAutogeneratedTestsBlock(opts: BuildTestsOptions): string {
  const { method, status, hasJsonObjectBody } = opts;
  const lines: string[] = [];

  if (typeof status === "number") {
    lines.push(`rq.test("Status code is ${status}", () => {\n  rq.response.to.have.status(${status});\n});`);
  }

  if (method) {
    lines.push(
      `rq.test("Request method is ${method}", () => {\n  rq.expect(rq.request.method).to.equal("${method}");\n});`
    );
  }

  if (hasJsonObjectBody) {
    lines.push(`rq.test("Response has valid JSON body", () => {\n  rq.response.to.have.jsonBody();\n});`);
    lines.push(
      `rq.test("Response body is JSON object", () => {\n  const parsed = JSON.parse(rq.response.body);\n  rq.expect(parsed).to.be.an("object").and.not.to.be.an("array");\n});`
    );
  }

  return lines.join("\n\n");
}

// Inject block at end of existing script (or create fresh script). Returns new script.
export function injectAutogeneratedTests(script: string | undefined, block: string): string {
  if (!script || !script.trim()) {
    return `${block}\n`;
  }
  if (hasTests(script)) {
    return script;
  }
  const trimmed = script.endsWith("\n") ? script : script + "\n";
  return `${trimmed}\n${block}\n`;
}
